// 负责管理跟账户相关的全局数据

import type { UserInfo,AccountType,LoginRegError } from "@/model/user"
import { userLogin } from "@/api/user_api"

interface State {
	uinfo:UserInfo|null
}

export default {
	namespaced:true, //开启模块的局部调用
	state:():State=>{
		return {uinfo:null}
	},
	// state:()=>({uinfo:null}),  //简写
	mutations:{
		// 登录成功后，修改state数据
		loginSuccess(state:State,info:UserInfo){
			state.uinfo = info
			uni.setStorage({
				key:'uinfo',
				data:info
			})
		},
		// 用户刷新后，使用本地用户信息
		init(state:State,info:UserInfo){
			state.uinfo = info
		},
		exit(state:State){
			state.uinfo = null
			uni.removeStorage({
				key:'uinfo'
			})
		}
	},
	actions:{
		// 负责发起登录异步请求
		async loginAction(context:any,{username,password}:AccountType){
			let title = '登录成功'
			try {
				let res = await userLogin(username,password)
				console.log('登录成功',res);
				context.commit('loginSuccess',res.data)
				uni.navigateBack({delta:1})
			} catch (err) {
				//TODO handle the exception
				title = (err as LoginRegError).data!.error
			}
			uni.showToast({
				title,
				icon:'none'
			})
		}
	}
}